﻿using System;
using System.Collections.ObjectModel;
using System.Reflection.PortableExecutable;
using Microsoft.Data.Sqlite;
using MyTinnyApi.model;
using Newtonsoft.Json;

namespace MyTinnyApi.util
{
	public class RequestUtil
	{
		public static Requests GetRequestsById(int id)
		{
			var dicResult = DbUtil.ExecuteReader($"select * from t_request where Id = {id}").First();
			var req = JsonConvert.DeserializeObject<Requests>(JsonConvert.SerializeObject(dicResult));

            var paramList = DbUtil.ExecuteReaderForType<RequestParam>($"select * from t_request_param where RequestId = {id} and ParamVersion = (SELECT MAX(ParamVersion) FROM t_request_param WHERE RequestId = {id}) order by ShowOrder");
            req.RequestParamList = paramList;

            var headerList = DbUtil.ExecuteReaderForType<RequestHeader>($"select * from t_request_header where RequestId = {id} and HeaderVersion = (SELECT MAX(HeaderVersion) FROM t_request_header WHERE RequestId = {id}) order by ShowOrder");
            req.RequestHeaderList = headerList;

			var bodyList = DbUtil.ExecuteReaderForType<RequestBody>($"select * from t_request_body where RequestId = {id} order by ShowOrder");

			if(bodyList?.Count > 0)
			{
				var body = bodyList[0];
				var bodyParamList = DbUtil.ExecuteReaderForType<RequestBodyParam>($"select * from t_request_body_param where BodyId = {body.Id} and ParamVersion = (SELECT MAX(ParamVersion) FROM t_request_param WHERE BodyId = {body.Id}) order by ShowOrder");
				body.BodyParams = bodyParamList;
				req.RequestBodyModel = body;
            }
			//req.RequestParamList = paramList;

			req.InitedFullInfo = true;

            return req;
		}

        public static int InsertRequest(Requests req, AppDbContext db)
        {
            int reqId = -1;
            //using (var db = new AppDbContext())
            //{
                //db.Database.EnsureCreated();
                db.Request.Add(req);
                db.SaveChanges();

                reqId = req.Id;

                req.RequestHeaderList?.ForEach(h =>
                {
                    h.RequestId = reqId;
                    db.RequestHeader.Add(h);
                });

                req.RequestParamList?.ForEach(p =>
                {
                    p.RequestId = reqId;
                    db.RequestParam.Add(p);
                });

                if(req.RequestBodyModel != null)
                {
                    db.RequestBody.Add(req.RequestBodyModel);
                }

                db.SaveChanges();

                if (req.RequestBodyModel != null)
                {
                    req.RequestBodyModel.BodyParams?.ForEach(bp =>
                    {
                        bp.BodyId = req.RequestBodyModel.Id;
                        db.RequestBodyParam.Add(bp);
                    });

                    db.SaveChanges();
                }
            //}

            return reqId;


            //int id = DbUtil.ExecuteInsert($"insert into t_request (FolderId, RequestName, RequestUrl, RequestMethod, Description, ShowOrder) values (@p1, @p2, @p3, @p4, @p5, (select COALESCE(MAX(ShowOrder) + 1, 1) from t_request))", new[]
            //{
            //    new SqliteParameter("@p1", req.FolderId),
            //    new SqliteParameter("@p2", req.RequestName),
            //    new SqliteParameter("@p3", req.RequestUrl),
            //    new SqliteParameter("@p4", req.RequestMethod),
            //    new SqliteParameter("@p5", req.Description)
            //});

            //foreach (var param in req.RequestParamList)
            //{
            //    param.RequestId = id;

            //    DbUtil.ExecuteInsert($"insert into t_request_param (RequestId, ParamVersion, InUse, ParamName, ParamValue, Description, ShowOrder) values (@p1, @p2, @p3, @p4, @p5, @p6, select COALESCE(MAX(ShowOrder) + 1, 1) from t_request_param)", new[]
            //    {
            //        new SqliteParameter("@p1", param.RequestId),
            //        new SqliteParameter("@p2", param.ParamVersion),
            //        new SqliteParameter("@p3", param.InUse),
            //        new SqliteParameter("@p4", param.ParamName),
            //        new SqliteParameter("@p5", param.ParamValue),
            //        new SqliteParameter("@p6", param.Description)
            //    });
            //}

            //foreach (var header in req.RequestHeaderList)
            //{
            //    header.RequestId = id;

            //    DbUtil.ExecuteInsert($"insert into t_request_param (RequestId, HeaderVersion, InUse, HeaderName, HeaderValue, Description, ShowOrder) values (@p1, @p2, @p3, @p4, @p5, @p6, select COALESCE(MAX(ShowOrder) + 1, 1) from t_request_param)", new[]
            //    {
            //        new SqliteParameter("@p1", header.RequestId),
            //        new SqliteParameter("@p2", header.HeaderVersion),
            //        new SqliteParameter("@p3", header.InUse),
            //        new SqliteParameter("@p4", header.HeaderName),
            //        new SqliteParameter("@p5", header.HeaderValue),
            //        new SqliteParameter("@p6", header.Description)
            //    });
            //}

            //var body = req.RequestBodyModel;
            //body.RequestId = id;
            //var bodyId = DbUtil.ExecuteInsert($"insert into t_request_body (RequestId, BodyVersion, InUse, BodyType, BodyContent) values (@p1, @p2, @p3, @p4, @p5)", new[]
            //{
            //        new SqliteParameter("@p1", body.RequestId),
            //        new SqliteParameter("@p2", body.BodyVersion),
            //        new SqliteParameter("@p3", body.InUse),
            //        new SqliteParameter("@p4", body.BodyType),
            //        new SqliteParameter("@p5", body.BodyContent)
            //});

            //foreach(var bp in req.RequestBodyModel.BodyParams)
            //{
            //    bp.BodyId = bodyId;

            //    DbUtil.ExecuteInsert($"insert into t_request_body_param (BodyId, ParamVersion, InUse, ParamName, ParamValue, BodyType, Description, ShowOrder) values (@p1, @p2, @p3, @p4, @p5, @p6, @p7, select COALESCE(MAX(ShowOrder) + 1, 1) from t_request_body_param)", new[]
            //    {
            //        new SqliteParameter("@p1", bp.BodyId),
            //        new SqliteParameter("@p2", bp.ParamVersion),
            //        new SqliteParameter("@p3", bp.InUse),
            //        new SqliteParameter("@p4", bp.ParamName),
            //        new SqliteParameter("@p5", bp.ParamValue),
            //        new SqliteParameter("@p6", bp.BodyType),
            //        new SqliteParameter("@p6", bp.Description)
            //    });
            //}

            //return id;
        }
	}
}

